package de.unistuttgart.iaaskpimonitoring.esper.processingmanagement.nodeImpl;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.espertech.esper.client.EPServiceProvider;

import de.unistuttgart.iaaskpimonitoring.esper.processingmanagement.MMOperatorNode;
import de.unistuttgart.iaaskpimonitoring.esper.processingmanagement.NodeFactory;
import de.unistuttgart.iaaskpimonitoring.esper.processingmanagement.NodeFactoryManager;

public class MinNodeFactory implements NodeFactory {

	public MMOperatorNode createNode(Element DOMElement,
			Element attachmentsElement, MMOperatorNode parent,
			EPServiceProvider EPService) {

		MMOperatorNode toReturn = new MMOperatorNode();

		// Attributes independent of the children
		toReturn.setOutputStreamName("min"
				+ (++MMOperatorNode.nodeLatestDistributedID));
		toReturn.setOutputMetric("min");

		toReturn.setParent(parent);

		/*
		 * Parameters to get : value, simpleConditionOperator, attributeName
		 */

		// toReturn.setParameters();
		// Children nodes not for atomic operator like state, duration, count
		// etc.
		NodeList childrenElements = DOMElement.getChildNodes();
		List<MMOperatorNode> children = new ArrayList<MMOperatorNode>(4);
		Element currentChildRoot = (Element) childrenElements.item(0);
		children.add(NodeFactoryManager.getInstance(
				currentChildRoot.getLocalName()).createNode(currentChildRoot,
				attachmentsElement, toReturn, EPService));

		toReturn.getChildren();
		toReturn.setChildren(children);

		String statementString = null;
		if (childrenElements.getLength() == 1) {
			statementString
					.concat("INSERT INTO "
							+ toReturn.getOutputStreamName()
							+ " SELECT "
							+ " min("
							+ toReturn.getChildren().get(0).getOutputMetric()
							+ ") AS min, "
							+ " de.unistuttgart.iaaskpimonitoring.esper.eventmanagement.EventUtils.addInCorrelationSet(processInstanceID) "
							+ " FROM "
							+ toReturn.getChildren().get(0)
									.getOutputStreamName());
		} else if (childrenElements.item(1).getNodeName().equals(
				"simpleCondition")) {
			statementString
					.concat("INSERT INTO "
							+ toReturn.getOutputStreamName()
							+ " SELECT "
							+ " min("
							+ toReturn.getChildren().get(0).getOutputMetric()
							+ ") AS min, "
							+ " de.unistuttgart.iaaskpimonitoring.esper.eventmanagement.EventUtils.addInCorrelationSet(processInstanceID) "
							+ " FROM "
							+ toReturn.getChildren().get(0)
									.getOutputStreamName() + "("
							+ toReturn.getParameters().get("simpleCondition")
							+ ")");
		}


		// Creation of the statement that is directly registered in the engine !
		toReturn.setStatement(EPService.getEPAdministrator().createEPL(
				statementString));

		return toReturn;
	}
}